package com.yxmadoc.umlproject.config.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.yxmadoc.umlproject.model.Customer;
import com.yxmadoc.umlproject.model.Repairer;
import com.yxmadoc.umlproject.service.CustomerService;
import com.yxmadoc.umlproject.service.RepairerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

public class SecurityInterceptor implements HandlerInterceptor {
	
	@Autowired
	private CustomerService customerService;
	@Autowired
	private RepairerService repairerService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

			String token = request.getHeader("token");
			
			if (token == null) {
				throw new RuntimeException("无token，请重新登录");
			}
			String userId;
			
			try {
				userId = JWT.decode(token).getAudience().get(0);
			} catch (JWTDecodeException e) {
				throw new RuntimeException("token无效，请重新登录");
			}

			Customer customer = customerService.findOne(userId);
			Repairer repairer = repairerService.findOne(userId);
			
			if(customer == null && repairer == null){
				throw new RuntimeException("用户不存在，请重新登录");

			}
			
			try {
				JWTVerifier verifier;
				if(customer != null){
					verifier = JWT.require(Algorithm.HMAC256(customer.getCustomerPassword())).build();
					try {
						verifier.verify(token);
						request.setAttribute("currentUser", customer);
						return true;
					} catch (JWTVerificationException e) {
						throw new RuntimeException("token无效，请重新登录");
					}
				}else{
					verifier = JWT.require(Algorithm.HMAC256(repairer.getRepairerPassword())).build();
					try {
						verifier.verify(token);
						request.setAttribute("currentUser", repairer);
						return true;
					} catch (JWTVerificationException e) {
						throw new RuntimeException("token无效，请重新登录");
					}
				}
				
			} catch (UnsupportedEncodingException ignore) {
			}

			return false;
	}
	
	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
	
	}
	
	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
	
	}
}
